package edu.bulsu.coe.nfc;

import java.nio.ByteBuffer;
import java.util.List;

import javax.smartcardio.Card;
import javax.smartcardio.CardChannel;
import javax.smartcardio.CardException;
import javax.smartcardio.CardNotPresentException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import javax.smartcardio.TerminalFactory;

public class NFC {
	TerminalFactory factory;
	List<CardTerminal> terminals;
	CardTerminal terminal;
	Card card;
	CardChannel channel;
	ResponseAPDU resp;

	public NFC() throws CardException{
		factory = TerminalFactory.getDefault();
		terminals = factory.terminals().list();
		terminal = terminals.get(0);
	}
	
	/*
	 * Waits for a card to get tapped on the reader, then  return it's GUID
	 * @return int CardNumber
	 */
	public int getCardNumber() throws CardException{
		while(true){
			try{
				card = terminal.connect("*");
				channel = card.getBasicChannel();
				resp = channel.transmit(new CommandAPDU(0xFF, 0xCA, 0x00, 0x00, 0x08));
				ByteBuffer buffer = ByteBuffer.wrap(resp.getData());
				int cardNumber = buffer.getInt();
				return cardNumber;
			}
			//[ERR] Code 311 NFC tag removed before GUID has been read
			catch(CardNotPresentException cnpe){
				//System.out.println("[NFC] Warning 311: Card immediately removed before GUID has been read");
				continue;
			}
		}
	}
}
